﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using StudentWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StudentWeb.Controllers
{
    [Authorize]
    public class StudentController : Controller
    {
        private readonly IStudentRepo _studentRepo;

        private readonly StudentContext _studentContext;

        public StudentController(StudentContext studentContext)
        {
            _studentContext = studentContext;
        }
        [AllowAnonymous]
        public IActionResult Index()
        {
            return View(_studentContext.Students.ToList());
        }
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                _studentContext.Add(student);
                _studentContext.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }

        public IActionResult Edit(long id)
        {
            var student = _studentContext.Students.Find(id);
            if (student == null)
            {
                return NotFound();
            }
            return View(student);
        }

        [HttpPost]
        public IActionResult Edit(Student student)
        {
            if (ModelState.IsValid)
            {
                _studentContext.Update(student);
                _studentContext.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }

        public IActionResult Details(long id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest("id值异常！");
            }
            else
            {
                var student = _studentContext.Students.Find(id);
                if (student != null)    
                {
                    return View(student);
                }
                else
                {
                    return NotFound("未找到该记录！");
                }
            }
        }

        public IActionResult Delete(long id)
        {
            var student = _studentContext.Students.Find(id);
            if (student == null)
            {
                return NotFound("为找到记录！");
            }
            return View(student);
        }

        [HttpPost]
        public IActionResult DeleteComfirm(long id)
        {
            var student = _studentContext.Students.Find(id);
            _studentContext.Remove(student);
            _studentContext.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}
